import { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom/dist/index';
import { getGoodDetail, getGoodList } from '@/api/good';
import { Good, GoodCategory, IPagination, PaginateReturn } from '../types';
import styled from './index.module.css';
import { useFetchCategory } from '../goods/useFetchCategory';
import { getCategory } from '@/api/category';
import CategoryList from '../components/category/categoryList';
import { Empty, message } from 'antd';
import GoodInfo from './components/goodInfo';
import RecommendItem from './components/recommendItem';
import DetailCarousel from './components/DetailCarousel';
import { fetchCreateOrUpdateCarts } from '@/api/cart';
import { IResponse } from '@/types';
import { ICart } from '../goods/types';
export default function Detail() {
    let params = useParams<{ id: string; category: string }>(); //获取通过params方式传递的参数
    let [good, setGood] = useState<Good>();
    const nav = useNavigate();
    const { data: goods, fetchData: getGoods } = useFetchCategory<
        IPagination,
        PaginateReturn<Good>
    >(getGoodList);
    const { data: category, fetchData: fetchCategory } = useFetchCategory<any, GoodCategory[]>(
        getCategory,
    );
    useEffect(() => {
        fetchCategory();
        getGoods({
            pageNumber: 1,
            pageSize: 20,
            category: params.category,
        });
        getGoodDetail<Good>(params.id as string)
            .then((res) => {
                setGood(res);
            })
            .catch((err) => {
                setGood(undefined);
            });
    }, []);
    const urlChange = useCallback((id: string) => {
        nav(`/goods/index?category=${id}`);
    }, []);
    const goDetail = useCallback((good: Good) => {
        nav(`/goods/detail/${good.id}`);
    }, []);

    const curCategoryName = useMemo(() => {
        const curCategory = category?.find((item) => item.id == params.category);
        return {
            name: curCategory?.name,
            id: curCategory?.id,
        };
    }, [category]);
    const addcart = useCallback((good: Good) => {
        fetchCreateOrUpdateCarts<ICart, IResponse>({
            good: good.id,
            num: 1,
            is_select: false,
        }).then((res) => {
            if (res.statusCode === 200) {
                message.success('添加成功');
            } else if (res.statusCode === 403) {
                localStorage.setItem('cur_good', JSON.stringify(good));
            } else {
                message.error('添加失败');
            }
        });
    }, []);
    return (
        <div className={styled.content}>
            <div
                style={{
                    background: '#3b82f6',
                    color: 'white',
                    padding: '10px 200px',
                    zIndex: 1,
                }}
            >
                <CategoryList
                    border={false}
                    urlChange={urlChange}
                    categories={category || []}
                ></CategoryList>
            </div>
            <div className={styled.container}>
                {good ? (
                    <>
                        <div className={styled.breadscream}>
                            <Link to={'/goods'}> Deals </Link>
                            <span> &gt;</span>
                            <Link to={'/goods/index?category=' + curCategoryName.id}>
                                {' '}
                                {curCategoryName.name}{' '}
                            </Link>
                            <span> &gt;</span>
                            <span className={styled.goodName}>
                                &nbsp; {good && good.description}{' '}
                            </span>
                        </div>
                        <GoodInfo good={good} goDetail={goDetail}></GoodInfo>
                    </>
                ) : (
                    <div className={styled.NotFound}>
                        <Empty />
                    </div>
                )}
                <h3 style={{ margin: '40px 0', fontSize: '20px' }}>Related Deals Recommendation</h3>
                <DetailCarousel addCart={addcart} recommendGoods={goods.items}></DetailCarousel>
                <div className={styled.recomendList}>
                    {goods.items?.map((good: Good, index) => {
                        return (
                            <RecommendItem
                                addCart={addcart}
                                key={index}
                                good={good}
                            ></RecommendItem>
                        );
                    })}
                </div>
            </div>
        </div>
    );
}
